<?php
namespace app\kefu\service;
use app\kefu\ServicefInit;
use app\kefu\model\KfChatLog as KfChatLogModel;

class Index extends Servicefinit
{
    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        // 客服信息

        $this->assign([
            'word' => db('kf_words')->select(),
            'groups' => db('kf_groups')->where('status', 1)->select(),
            'status' => 1,
            // 'status' => db('kf_config')->where('id', 1)->find()
        ]);

        return $this->fetch('service/index');
    }

    // 获取服务用户列表
    // 此方法是为了防止客服工作期间错误的刷新工作台，导致服务人员消失的问题
    public function getUserList()
    {
        if (request()->isAjax()) {

            // 此处只查询过去 三个小时 内的未服务完的用户
            $userList = db('service_log')->field('user_id id,user_name name,user_avatar avatar,user_ip ip')
                ->where('kf_id', cookie('l_user_id'))
                ->where('start_time', '>', time() - 3600 * 3)->where('end_time', 0)->select();

            return json(['code' => 1, 'data' => $userList, 'msg' => 'ok']);
        }
    }

    // 获取聊天记录
    public function getChatLog()
    {
         if (request()->isAjax()) {

            $guest_code = input("guest_code");
            $list = KfChatLogModel::whereOr(['from_code'=>$guest_code,'to_code'=>$guest_code])->limit(10)->order('id ASC')->select();
 
            

            return $this->success('',null,$list);
         }
    }

    // ip 定位
    public function getCity()
    {
        $ip = input('param.ip');

        $ip2region = new \Ip2Region();
        $info = $ip2region->btreeSearch($ip);

        $city = explode('|', $info['region']);

        if (0 != $info['city_id']) {
            return json(['code' => 1, 'data' => $city['2'] . $city['3'] . $city['4'], 'msg' => 'ok']);
        } else {

            return json(['code' => 1, 'data' => $city['0'], 'msg' => 'ok']);
        }
    }
}
